<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .nav>ul {
            display: flex;
            width: 480px;
            margin: auto;
            position: relative;
        }

        li {
            width: 80px;
            padding: 10px;
            list-style-type: none;
            text-align: center;
            color: black;
            font-weight: 500;
            height: 20px;
            font-size: 18px;
            line-height: 20px;
        }

        .box {
            background-color: rgba(172, 255, 47, 0.459);
            width: 100px;
            height: 40px;
            position: absolute;
            z-index: -1;
            transform: translateX();
            transition: transform 1s;
        }
    </style>
</head>

<body>
    <div class="nav">
        <ul>
            <div class="box"></div>
            <li>首页</li>
            <li>导航</li>
            <li>测试</li>
            <li>测试</li>
        </ul>
    </div>
</body>
<script>
    window.onload = () => {
        var ul = document.querySelector('.nav>ul')
        var box = document.getElementsByClassName('box')
        var frist = 0
        box = box[0]
        ul.addEventListener('mouseover', function (e) {
            console.log(e.target.offsetLeft);
            animation(box, e.target.offsetLeft);
        })
        ul.addEventListener('mouseout', function (e) {
            animation(box, frist);
        })
        ul.addEventListener('click',function(e){
            frist =  e.target.offsetLeft
            animation(box, frist);
        })
    }
    function animation(element, position) {
        element.style.transform = `translateX(${position}px)`
    }
</script>

</html>